import { addTag, editTag, getList, getTagList } from '@/services/tag'
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components'
import { Button, Form, Input, Modal, Select, Spin, Tag } from 'antd'
import { connect } from 'dva'
import debounce from 'lodash/debounce'
import { default as React, useMemo, useRef, useState } from 'react'
import router from 'umi/router'
import { deleteTag } from '@/services/tag'

const organization = () => {
  const columns = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '标签名称',
      dataIndex: 'labelName',
    },
    {
      title: '标签类型',
      dataIndex: 'labelType',
      valueType: 'select',
      valueEnum: {
        '-1': { text: '全部' },
        '0': { text: '实体类型' },
        '1': { text: '事件类型' },
      },
    },
    {
      title: '词库映射',
      key: 'mappingCharList',
      search: false,
      width: 214,
      render: (text, record) => {
        console.log(record.mappingCharList)
        return record.mappingCharList.map((item, index) => {
          if (index < 1) {
            return (
              <Tag color="blue" key={item.dictionaryLabelId}>
                {item.dictionaryLabelName}
              </Tag>
            )
          }
          if (index === 1) {
            return (
              <>
                <Tag color="blue" key={item.dictionaryLabelId}>
                  {item.dictionaryLabelName}
                </Tag>
                {record.mappingCharList.length - 2 === 0 ? null : (
                  <span style={{ color: '#3371D8' }}>{`[+${record.mappingCharList.length - 2}]`}</span>
                )}
              </>
            )
          }
        })
      },
    },
    {
      title: '规则配置',
      key: 'ruleConfigList',
      width: 312,
      search: false,
      render: (text, record) => {
        return record.ruleConfigList.map((item, index) => {
          if (index === 0 && record.labelType === 0) {
            return (
              <div key={item.expressionText} style={{ display: 'flex' }}>
                <span
                  style={{
                    display: 'inline-block',
                    maxWidth: '312px',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {item.expressionText}
                </span>
                {record.ruleConfigList.length - 1 === 0 ? null : (
                  <span style={{ color: '#3371D8' }}>{`[+${record.ruleConfigList.length - 1}]`}</span>
                )}
              </div>
            )
          } else if (record.labelType === 1) {
            let str = record.ruleConfigList.map((item) => item.expressionText).join('、')
            str = '触发词' + str
            if (index === 0) {
              return (
                <div key={index}>
                  <div
                    style={{
                      width: '312px',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {str}
                  </div>
                </div>
              )
            }
          }
        })
      },
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            console.log('record', record)
            setNowEditList(record)
            setValue(
              record.mappingCharList.map((item) => {
                return {
                  value: item.dictionaryLabelName,
                  key: item.dictionaryLabelId,
                }
              }),
            )
            showEditModal()
          }}
        >
          编辑
        </a>,
        <a
          key="view"
          onClick={() => {
            router.push(`/resource/addOrganization/${record.id}/${record.labelType}`)
          }}
        >
          配置
        </a>,
        <a
          key="delate"
          onClick={async () => {
            const res = await deleteTag({ ids: record.id })
            table.current?.reload()
          }}
        >
          删除
        </a>,
      ],
    },
  ]
  // const { dispatch } = props
  const [nowEditList, setNowEditList] = React.useState({ mappingCharList: [] })
  //编辑弹出框
  const [openEdit, setOpenEdit] = React.useState(false)

  function showEditModal() {
    setOpenEdit(true)
  }

  const hideEditModal = async () => {
    setOpenEdit(false)
  }
  const onFinish = async (value) => {
    console.log(
      value.labelType === 0
        ? {
            ...value,
            id: nowEditList.id,
            mappingCharList: tagValue.map((item) => {
              return {
                dictionaryLabelId: item.key?.toString(),
              }
            }),
          }
        : { ...value },
    )
    const res = await editTag(
      value.labelType === 0
        ? {
            ...value,
            id: nowEditList.id,
            mappingCharList: tagValue.map((item) => {
              return {
                dictionaryLabelId: item.key,
              }
            }),
          }
        : { ...value, id: nowEditList.id },
    )
    console.log('修改成功', res)
    table.current?.reload()
    hideEditModal()
  }
  const onAddFinish = async (value) => {
    setNowEditList({ mappingCharList: [] })
    console.log('新增标签', {
      labelName: value.labelName,
      labelType: value.labelType,
      mappingCharList: addNewTagValue?.map((item) => {
        return {
          dictionaryLabelId: item.key,
        }
      }),
    })
    const res = await addTag(
      value.labelType === 0
        ? {
            labelName: value.labelName,
            labelType: value.labelType,
            mappingCharList: addNewTagValue.map((item) => {
              return {
                dictionaryLabelId: item.key,
              }
            }),
          }
        : { labelName: value.labelName, labelType: value.labelType },
    )
    console.log('新增成功', res)
    table.current?.reload()
    hideAddNewTag()
  }

  function DebounceSelect({ fetchOptions, debounceTimeout = 800, ...props }) {
    const [fetching, setFetching] = useState(false)
    const [options, setOptions] = useState([])
    const fetchRef = useRef(0)
    const debounceFetcher = useMemo(() => {
      const loadOptions = (value) => {
        fetchRef.current += 1
        const fetchId = fetchRef.current
        setOptions([])
        setFetching(true)
        fetchOptions(value).then((newOptions) => {
          if (fetchId !== fetchRef.current) {
            // for fetch callback order
            return
          }
          console.log(newOptions, 'newOptions')
          setOptions(newOptions)
          setFetching(false)
        })
      }

      return debounce(loadOptions, debounceTimeout)
    }, [fetchOptions, debounceTimeout])
    return (
      <Select
        labelInValue
        filterOption={false}
        onSearch={debounceFetcher}
        notFoundContent={fetching ? <Spin size="small" /> : null}
        {...props}
        options={options}
      />
    )
  } // Usage of DebounceSelect

  async function fetchUserList(name) {
    console.log('搜索', name)
    // return fetch('/nlp/dictionary/label/list', {
    //   method: 'POST',
    //   body: JSON.stringify({ dictionaryLabelName: name }),
    // })
    //   .then((response) => response.json())
    const res = await getList({ dictionaryLabelName: name })
    console.log(res)
    return res.data?.map((item) => ({
      key: `${item.dictionaryLabelId}`,
      value: item.dictionaryLabelName,
    }))
  }
  const [tagValue, setValue] = useState([])
  const [addNewTagValue, setAddNewTagValue] = useState([])
  const [openAddNewTag, setOpenAddNewTag] = React.useState(false)
  const hideAddNewTag = () => {
    setAddNewType(null)
    setOpenAddNewTag(false)
  }
  function showAddNewTag() {
    setOpenAddNewTag(true)
  }
  const table = useRef()
  const [addNewType, setAddNewType] = React.useState(-1)
  return (
    <div>
      <Modal
        destroyOnClose
        title="编辑标签"
        open={openEdit}
        onOk={hideEditModal}
        onCancel={hideEditModal}
        footer={null}
      >
        <Form initialValues={nowEditList} onFinish={onFinish} labelCol={{ span: 4, offset: 1 }}>
          <Form.Item
            label="标签名称"
            name="labelName"
            required
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="装备" />
          </Form.Item>
          <Form.Item
            label="标签类型"
            name="labelType"
            required
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select
              disabled
              placeholder="请选择标签类型"
              onSelect={(value) => {
                setNowEditList({ ...nowEditList, labelType: value })
              }}
            >
              <Select.Option value={0}>实体类型</Select.Option>
              <Select.Option value={1}>事件类型</Select.Option>
            </Select>
          </Form.Item>
          {nowEditList?.labelType === 0 ? (
            <Form.Item label="词库映射">
              <DebounceSelect
                mode="multiple"
                value={tagValue}
                placeholder="Select users"
                fetchOptions={fetchUserList}
                onChange={(newValue) => {
                  setValue(newValue)
                }}
                style={{ width: '100%' }}
              />
            </Form.Item>
          ) : null}
          <Form.Item>
            <div
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'end',
              }}
            >
              <Button onClick={hideEditModal} style={{ marginRight: '20px' }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        destroyOnClose
        title="新增标签"
        open={openAddNewTag}
        onOk={hideAddNewTag}
        onCancel={hideAddNewTag}
        footer={null}
      >
        <Form onFinish={onAddFinish} labelCol={{ span: 4, offset: 1 }}>
          <Form.Item
            label="标签名称"
            name="labelName"
            required
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="装备" />
          </Form.Item>
          <Form.Item
            label="标签类型"
            name="labelType"
            required
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select
              placeholder="请选择标签类型"
              onSelect={(value) => {
                setAddNewType(value)
              }}
            >
              <Select.Option value={0}>实体类型</Select.Option>
              <Select.Option value={1}>事件类型</Select.Option>
            </Select>
          </Form.Item>
          {addNewType === 0 ? (
            <Form.Item label="词库映射">
              <DebounceSelect
                mode="multiple"
                value={addNewTagValue}
                placeholder="Select users"
                fetchOptions={fetchUserList}
                onChange={(newValue) => {
                  setAddNewTagValue(newValue)
                }}
                style={{ width: '100%' }}
              />
            </Form.Item>
          ) : null}
          <Form.Item style={{ display: 'flex', justifyContent: 'end' }}>
            <Button onClick={hideEditModal} style={{ marginRight: '20px' }}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <ProTable
        actionRef={table}
        request={async (params) => {
          const res = await getTagList({
            pageNum: params.current - 1,
            pagesize: params.pageSize,
            data: {
              labelName: params?.labelName,
              labelType: params?.labelType ?? -1,
              showRule: true,
              showMapping: true,
            },
          })
          console.log(res.data.list)
          return {
            data: res.data.list,
            success: true,
            total: res.data.total,
          }
        }}
        columns={columns}
        rowKey="id"
        toolbar={{
          actions: [
            <Button
              key="key"
              type="primary"
              onClick={() => {
                setAddNewTagValue([])
                showAddNewTag()
              }}
            >
              新增
            </Button>,
          ],
          settings: [],
        }}
        pagination={{
          pageSize: 10,
        }}
        headerTitle="标签列表"
      />
    </div>
  )
}
export default connect(({ tabmessages }) => ({
  okgLocation: tabmessages.changeOkgLocation,
}))(organization)
